package com.itheima.service.impl;

import com.itheima.common.dto.MessageDTO;
import com.itheima.common.exception.LoginException;
import com.itheima.mapper.MobileMemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MobileMemberMapper memberMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录功能实现
     * @param messageDTO
     */
    @Override
    public void memberLogin(MessageDTO messageDTO) {
        // (2）从redis中获取验证码
        Integer code = (Integer) redisTemplate.opsForValue().get(messageDTO.getTelephone());
        //（1）判断验证码是否为空，如果为空则登录失败
        if(code == null){
            throw new LoginException("验证码已过期");
        }
        //（3）校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        if(!code.equals(messageDTO.getValidateCode())){
            throw new LoginException("验证码输入错误");
        }
        //（4） 如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
        Member member = memberMapper.findMemberByTelephone(messageDTO.getTelephone());
        if (member == null){
            member = Member.builder()
                    .phoneNumber(messageDTO.getTelephone())
                    .build();
            memberMapper.insertMember(member);
        }
    }
}
